package com.itdaan.portal.common.util;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

/**
 * @author www.itdaan.com
 */
@SuppressWarnings({ "unchecked" })
public class JsonUtil {
	private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
	public static final String ENCODE_UTF8 = "UTF-8";
	public static final String ENCODE_GBK = "GBK";
	/**
	 * 性能方面 JackSon > Gson > Json 故这里决定使用JackSon 将Collection转换为Json
	 * 参数是Collection
	 * 
	 * @param collection
	 */
	public static String toJson(Collection<Object> collection) {
		/*
		 * 使用Gson的方式
		 * Gson gson = new Gson();
		 * String json = gson.toJson(map);
		 */
		/*
		 * 使用Jackson的方式
		 */
		String json = "[]";
		try {
			// ObjectMapper mapper = new ObjectMapper();
			// StringWriter sw = new StringWriter();
			// JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
			// mapper.writeValue(gen, collection);
			// gen.close();
			// json = sw.toString();
			ObjectMapper mapper = new ObjectMapper();
			json = mapper.writeValueAsString(collection);
		} catch (JsonGenerationException e) {
			json = "[]";
			logger.error("------1------ toJson JsonGenerationException error:\n", e);
		} catch (JsonMappingException e) {
			json = "[]";
			logger.error("------2------ toJson JsonMappingException error:\n", e);
		} catch (IOException e) {
			json = "[]";
			logger.error("------3------ toJson IOException error:\n", e);
		}
		return json;
	}

	/**
	 * @Title: toJson
	 * @Description: 将对象转换为Json数据
	 * @param @param obj
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	public static String toJson(Object obj) {
		String json = "[]";
		try {
			// ObjectMapper mapper = new ObjectMapper();
			// StringWriter sw = new StringWriter();
			// JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
			// mapper.writeValue(gen, obj);
			// gen.close();
			// json = sw.toString();
			ObjectMapper mapper = new ObjectMapper();
			json = mapper.writeValueAsString(obj);
		} catch (JsonGenerationException e) {
			json = "[]";
			logger.error("------1------ toJson IOException error:\n", e);
		} catch (JsonMappingException e) {
			json = "[]";
			logger.error("------2------ toJson IOException error:\n", e);
		} catch (IOException e) {
			json = "[]";
			logger.error("------3------ toJson IOException error:\n", e);
		}
		return json;
	}

	/**
	 * 将MAP转为Json Map参数
	 * 
	 * @param map
	 * @return
	 * @throws IOException
	 */
	public static String toJson(Map<String, Object> map) {
		String json = "[]";
		try {
			// ObjectMapper mapper = new ObjectMapper();
			// StringWriter sw = new StringWriter();
			// JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
			// mapper.writeValue(gen, map);
			// gen.close();
			// json = sw.toString();
			ObjectMapper mapper = new ObjectMapper();
			json = mapper.writeValueAsString(map);
		} catch (JsonGenerationException e) {
			json = "[]";
			logger.error("----1------toJson JsonGenerationException:\n" + e);
		} catch (JsonMappingException e) {
			json = "[]";
			logger.error("----2------toJson JsonMappingException:\n" + e);
		} catch (IOException e) {
			json = "[]";
			logger.error("----3------toJson IOException:\n" + e);
		}
		return json;
	}

	/**
	 * 将JSON字符串 转换为对象
	 * 
	 * @author weiyuanhua
	 * @date 2010-11-18 下午02:52:13
	 * @param jsonStr
	 *            JSON字符串
	 * @param beanClass
	 *            泛型对象
	 * @param field
	 *            对象中需要忽略的属性
	 * @return
	 */
	public static Object jsonToObject(String jsonStr, Class<?> beanClass) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		return objectMapper.readValue(jsonStr.getBytes(), beanClass);
	}

	public static Object jsonToObject(String jsonStr, String encoding, Class<?> beanClass) throws JsonParseException, JsonMappingException,
			IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		return objectMapper.readValue(jsonStr.getBytes(encoding), beanClass);
	}

	public static Map<String, Object> parseJSON2Map(String jsonStr) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		return objectMapper.readValue(jsonStr, Map.class);
	}

	// 不需要记性属性的忽略
	public static String toJson(Object object, String filterName) {
		String json = "[]";
		try {
			ObjectMapper mapper = new ObjectMapper();
			FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName, SimpleBeanPropertyFilter.serializeAllExcept());
			json = mapper.writer(filterProvider).writeValueAsString(object);
		} catch (Exception e) {
			json = "[]";
			logger.error("----1------toJson Exception:\n" + e);
		}
		return json;
	}

	/*
	 * @param object 需要进行json序列化的类 可以是任何复杂的类
	 * @param args 需要进行过滤的属性名称 类对象名称或者一些属性名称都可以进行过滤
	 */
	public static String toJson(Object object, String[] args, String filterName) {
		String json = "[]";
		try {
			ObjectMapper mapper = new ObjectMapper();
			FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName,
					SimpleBeanPropertyFilter.serializeAllExcept(args));
			json = mapper.writer(filterProvider).writeValueAsString(object);
		} catch (Exception e) {
			json = "[]";
			logger.error("----1------toJson Exception:\n" + e);
		}
		return json;
	}
	// public static void main1(String[] args) {
	// User user = new User(12, "aaa", "123456", new Date());
	// // String result = toJson(user, "id");
	// String result = toJson(user);
	// System.out.println(result);
	// List list = new ArrayList();
	// list.add(0, "name");
	// list.add(1, "favorite");
	// String li = toJson(list);
	// System.out.println(li);
	// Map<String, String> map = new HashMap<String, String>();
	// map.put("password", "123");
	// map.put("name", "clark");
	// map.put("call", "wowo");
	// String mr = toJson(map);
	// System.out.println(mr);
	// // Date d = new Date();
	// String jsonStr = "{\"id\":23,\"name\":\"44444\"}";
	// try {
	// User u = (User) jsonToObject(jsonStr, User.class);
	// System.out.println(u.getName());
	// Map<String, Object> mapResult = parseJSON2Map(jsonStr);
	// Set<String> key = mapResult.keySet();
	// Iterator iter = key.iterator();
	// while (iter.hasNext()) {
	// String k = (String) iter.next();
	// System.out.println(mapResult.get(k));
	// }
	// } catch (JsonParseException e) {
	// e.printStackTrace();
	// } catch (JsonMappingException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	//
	// public static void main(String[] args) throws IOException {
	// User user = new User();
	// user.setName("菠萝大象");
	// user.setGender(GenderEnum.MALE);
	// List<Account> accounts = new ArrayList<Account>();
	// Account account = new Account();
	// account.setId(1);
	// account.setBalance(BigDecimal.valueOf(1900.2));
	// account.setCardId("423335533434");
	// account.setDate(new Date());
	// accounts.add(account);
	// account = new Account();
	// account.setId(2);
	// account.setBalance(BigDecimal.valueOf(5000));
	// account.setCardId("625444548433");
	// account.setDate(new Date());
	// accounts.add(account);
	// user.setAccounts(accounts);
	// ObjectMapper mapper = new ObjectMapper();
	// // mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, Boolean.TRUE);
	// String json = mapper.writeValueAsString(user);
	// System.out.println("Java2Json: " + json);
	// user = mapper.readValue(json, User.class);
	// System.out.println("Json2Java: " + mapper.writeValueAsString(user));
	// }
}
